package com.yqb.study.util;

import java.util.Map;
import java.util.Map.Entry;

import com.yqb.study.common.warpper.log.BaseLogWarpperMap;
import com.yqb.study.constant.cache.impl.DictFactory;
import com.yqb.study.support.StrKit;

/**
 * 日志包裹处理类
 */
public class LogContrastUtil {
	// 分隔符
    public static final String separator = ";";

	/**
	 * 包裹字段名
	 * @return
	 */
	private static String warpperFieldName(BaseLogWarpperMap logWarpperMap, String fieldEn) {
		String fieldCn = logWarpperMap.getFieldWarpper(fieldEn);
		if (ToolUtil.isNotEmpty(fieldCn)) {
			return fieldCn;
		} else {
			return fieldEn;
		}		
	}
	
	/**
	 * 包裹字段值
	 * @return
	 */
	private static String warpperFieldVal(BaseLogWarpperMap logWarpperMap, String fieldEn, String fieldVal) {
		String baseInfoClassName = logWarpperMap.getFieldNumWarpper(fieldEn);
		if (ToolUtil.isNotEmpty(baseInfoClassName)) {
			String fieldValCn = DictFactory.me().getNum2NameDicts(baseInfoClassName).get(fieldVal);

			if (ToolUtil.isNotEmpty(fieldValCn)) {
				return fieldValCn;
			} else {
				return fieldVal;
			}
		} else {
			return fieldVal;
		}		
	}	
	
	/**
	 * warpper请求参数的字段名称和字段值
	 * @param logWarpperMap
	 * @param requests
	 * @return
	 */
	public static String parseLogField(BaseLogWarpperMap logWarpperMap, Map<String, String> requests) {

		StringBuilder sb = new StringBuilder();
		for (Entry<String, String> requestItem : requests.entrySet()) {
			String fieldEn = requestItem.getKey();
			String fieldVal = requestItem.getValue();

			// 包裹字段名
			sb.append(warpperFieldName(logWarpperMap, fieldEn) + "=");

			// 包裹字段值
			sb.append(warpperFieldVal(logWarpperMap, fieldEn, fieldVal) + separator);
		}
		return StrKit.removeSuffix(sb.toString(), separator);
	}
	
	/**
	 * 比较原对象与修改信息,并输出不一致信息
	 */
	public static String contrastObj(BaseLogWarpperMap logWarpperMap, Object originObj, Map<String, String> requests) {
		// 获取未修改前变量
		Map<String, Object> originObjMap = ReflexObjectUtil.getKeyAndValue(originObj);
		
		StringBuilder sb = new StringBuilder();
		for (Entry<String, String> requestItem : requests.entrySet()) {
			String fieldEn = requestItem.getKey();
			String fieldVal = requestItem.getValue();

			// 包裹字段名
			sb.append(warpperFieldName(logWarpperMap, fieldEn) + "=");

			if (originObjMap.containsKey(fieldEn) && !ToolUtil.equalsAsString(originObjMap.get(fieldEn), fieldVal)) {
				// 字段值有修改
				sb.append(String.format("[%s]->[%s]", warpperFieldVal(logWarpperMap, fieldEn, originObjMap.get(fieldEn).toString()), warpperFieldVal(logWarpperMap, fieldEn, fieldVal)));
			} else {
				// 字段值无修改
				sb.append(warpperFieldVal(logWarpperMap, fieldEn, fieldVal));
			}

			sb.append(separator);
		}
		return StrKit.removeSuffix(sb.toString(), separator);
	}
}